import axios from 'axios'
import{ElMessage} from "element-plus";
import { useRouter } from 'vue-router';
import qs from 'qs';
import router from "@/router/index.js";
axios.defaults.withCredentials = true;
axios.defaults.baseURL = 'http://localhost:8080';
const defaultFailure = (message,code,url)=>{
    console.warn(`请求地址：${url},状态码:${code},错误信息:${message}`)
    ElMessage.warning(message)
}
const defaultError = (message,code,url)=>{
    console.error(err)
    ElMessage.warning('发生了一些错误！')
}

function internalPost(url,data,header,success,failure,error = defaultError){
    axios.post(url,data,{headers:header}).then(({data}) => {
        if(data.code == 200){
            success(data.data)
        }else{
            failure(data.message,data.code,url)
        }
    }).catch(err => error(err))
}
function internalGet(url,data,header,success,failure,error = defaultError){
    axios.Get(url,data,{headers:header}).then(({data}) => {
        if(data.code == 200){
            success(data.data)
        }else{
            failure(data.message,data.code,url)
        }
    }).catch(err => error(err))
}
function login(username, password, success, failure = defaultFailure) {
    const formData = qs.stringify({
        username: username,
        password: password
    });
    internalPost('http://localhost:8080/login', formData, {
        'Content-Type': 'application/x-www-form-urlencoded'
    }, (response) => {
        const { status, headers } = response;
        console.log(response);
        console.log('实际状态码:', status);
        console.log('实际重定向地址:', headers.location);
        if (status === 302 && headers.location === 'http://localhost:8080/') {
            const router = useRouter();
            router.push('/welcome/home'); // 根据实际路由配置调整路径，确保能跳转到home.vue页面
            return;
        }
        if (response.data.code === 200) {
            ElMessage.success(`登录成功，欢迎 ${response.data.username}`);
            success(response.data);
            const router = useRouter();
            router.push('/home');
        } else {
            failure(response.data.message, response.data.code, 'http://localhost:8080/login');
        }
    }, failure);
}
export { login };